package com.action;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class UploadAction extends ActionSupport {
	private List<File> uploadify;
	private List<String> uploadifyFileName;
	private List<String> uploadifyContentType;

	@Override
	public String execute() throws Exception {
		//System.out.println("uploadify:" + uploadify.size() + "uploadifyFileName:" 
		//		+ uploadifyFileName.size() + "uploadifyContentType:" + uploadifyContentType.size());
		
		// 上传文件
		ServletContext servletContext = ServletActionContext.getServletContext();
		if (uploadify != null) {
			String dataDir = servletContext.getRealPath("/upload/housePhoto");
			for (int i = 0; i < uploadify.size(); i++) {
				File file = uploadify.get(i);
				System.out.println("=======" + uploadifyFileName.get(i));
				String fileName = System.currentTimeMillis() 
					+ uploadifyFileName.get(i).substring(uploadifyFileName.get(i).indexOf("."));
				File saveFile = new File(new File(dataDir), fileName);
				if (!saveFile.getParentFile().exists())
					saveFile.mkdirs();
				FileUtils.copyFile(file, saveFile);
				Map<String, Object> sessionMap = ActionContext.getContext().getSession();
				sessionMap.put("photoName", fileName);
			}
		}
		
		/*if (uploadify != null) {
			String dataDir = servletContext.getRealPath("/upload/housePhoto");
			uploadifyFileName = System.currentTimeMillis() + uploadifyFileName.substring(uploadifyFileName.indexOf("."));
			File saveFile = new File(new File(dataDir), uploadifyFileName);
			if (!saveFile.getParentFile().exists())
				saveFile.mkdirs();
			try {
				FileUtils.copyFile(uploadify, saveFile);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}*/
		return null;
	}

	public List<File> getUploadify() {
		return uploadify;
	}

	public void setUploadify(List<File> uploadify) {
		this.uploadify = uploadify;
	}

	public List<String> getUploadifyFileName() {
		return uploadifyFileName;
	}

	public void setUploadifyFileName(List<String> uploadifyFileName) {
		this.uploadifyFileName = uploadifyFileName;
	}

	public List<String> getUploadifyContentType() {
		return uploadifyContentType;
	}

	public void setUploadifyContentType(List<String> uploadifyContentType) {
		this.uploadifyContentType = uploadifyContentType;
	}

}
